<template>
    <el-dialog v-model="show" title="烫金稿上传" align-center width="40%" @close="handleClose">
        <el-row :gutter="20" class="mb8" justify="space-between">
            <el-col :span="8">
                客户名称：{{ props.initList.customerName || '' }}
            </el-col>
            <el-col :span="8" style="text-align: right;">
                产品名称：F款长方形餐具套装
            </el-col>
        </el-row>

        <div v-for="(item, index) in list" :key="index">
            <el-row :gutter="20" justify="space-between">
                <el-col :span="8">
                    <el-tooltip class="box-item" effect="dark" :content="item.gildingName" placement="top-start">
                        <h4 class="lint"><strong>{{ item.gildingName }}</strong></h4>
                    </el-tooltip>
                </el-col>
                <el-col :span="12" style="display: flex; align-items: center;">
                    <h4>选择现有烫金版：</h4>
                    <el-select @change="selectGilding($event, index)" v-model="item.dictName" placeholder="请选择烫金版">
                        <el-option v-for="(dict, dictIndex) in gildingAllList" :key="dictIndex"
                            :label="dict.gildingName" :value="dict.index" />
                    </el-select>
                </el-col>
                <el-col :span="4" style="display: flex; align-items: center;">
                    <h4>新烫金版:</h4>
                    <el-switch v-model="item.addFlagShow" />
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="6" class="mb20">
                    <el-upload class="upload-demo" :show-file-list="false" drag :action="uploadImgUrl"
                        :headers="headers" multiple :auto-upload="true"
                        :on-success="(response: any, file: any, fileList: any) => { return handlBottomSuccess(response, file, fileList, index) }"
                        :before-upload="beforeBottomUpload">
                        <uploadStyle icon="PictureFilled" />
                    </el-upload>
                </el-col>
                <el-col :span="6" class="mb20" v-for="(fileItem, fileIndex) in item.fileList" :key="fileIndex">
                    <div class="upload_img">
                        <img class="upload_img_bdr" :src="fileItem.fileUrl" alt="">
                        <el-button @click="handleDelete(index, fileIndex)" size="small" class="upload_img_del"
                            type="danger" icon="CloseBold" circle />
                    </div>
                </el-col>
            </el-row>

            <el-row :gutter="20" justify="space-between">
                <el-col style="display: flex; align-items: center;">
                    <div style="width: 40px;">备注:</div>
                    <el-input v-model="item.remark" style="width: 100%" placeholder="请输入备注" />
                </el-col>
            </el-row>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="handleSubmit">确 认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { type UploadProps } from 'element-plus';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import uploadStyle from './uploadStyle.vue';
import { getGildingUploadInfoApi, getGildingInfoAllApi, addGildingInfoApi, editGildingInfoApi } from '@/api/sj/productManagement/designerTakesOrders/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList']);
const emits = defineEmits(['submit', 'close']);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const dialogVisible = ref();

const aFrontCoverImgList = ref<string[]>([]);
const aFrontCoverIndex = ref<number>(NaN);

const hatImgList = ref<string[]>([]);
const hatIndex = ref<number>(NaN);
const show = ref(false);
const list = ref<any>([]);
const flag = ref(''); // 1 新增 2 修改
const gildingAllList = ref<any>([]);

watch(() => props.visible, async (newValue) => {
    show.value = props.visible
    if (newValue) {
        getDetails()
        getGildingInfoAll()
    }
}, { deep: true });

/** 获取上传详情 */
const getDetails = async () => {
    const { code, data } = await getGildingUploadInfoApi(props.initList.id);
    if (code == 200) {
        data.dataList.forEach((element: any) => {
            element.dictName = ''
            if (element.dataList != null) {
                element.fileList = element.dataList
            } else {
                element.fileList = []
            }

            if(element.addFlag == 1) {
                element.addFlagShow = true
            }else {
                element.addFlagShow = false
            }
        });
        list.value = data.dataList
        flag.value = data.flag
    }
};

/** 获取全部的 烫金版 */
const getGildingInfoAll = async () => {
    const { code, data } = await getGildingInfoAllApi();
    if (code == 200) {
        data.forEach((element: any, index: number) => {
            element.index = index
        });

        gildingAllList.value = data
    }
};

/** 选择现有的烫金版 */
const selectGilding = (value: any, index: any) => {
    gildingAllList.value.forEach((element: any) => {
        if (element.index == value) {
            list.value[index].fileList = element.dataList
        }
    });
};

const handlBottomSuccess: any = (
    response: { data: { url: any; }; }, file: any, fileList: any, index: any
) => {
    dialogVisible.value.close()
    if (list.value[index].dictName) {
        list.value[index].fileList = [{
            fileUrl: response.data.url
        }]

        list.value[index].dictName = ''
    } else {
        list.value[index].fileList.push({
            fileUrl: response.data.url
        })
    }
};

const beforeBottomUpload: UploadProps['beforeUpload'] = () => {
    dialogVisible.value = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
};

// 删除图片
const handleDelete = async (index: number, fileIndex: number) => {
    ElMessageBox.confirm(
        '确定要删除选中的图片吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            list.value[index].fileList.splice(fileIndex, 1);
            ElMessage({
                type: 'success',
                message: '删除成功!',
            })
        })
        .catch(() => {

        })

};




const handleSubmit = async () => {
    let showType = false
    for (const item of list.value) {
        if (item.fileList.length == 0) {
            proxy?.$modal.msgError(`请上传${item.gildingName}的烫金稿`);
            showType = true
            break;
        }
    }

    if (showType) return

    // emits('submit', false);

    if (flag.value == '1') {
        handleAddSubmit(1)
    } else {
        handleAddSubmit(2)
    }
    // proxy?.$modal.msgSuccess('新增成功');
};

/** 提交新增 */
const handleAddSubmit = async (index: number) => {
    let data: any = []
    list.value.forEach((item: any) => {
        data.push({
            customizedProductId: props.initList.id,
            gildingName: item.gildingName,
            productId: item.productId,
            id: index == 2 ? item.id : '',
            fileList: item.fileList,
            remark: item.remark,
            addFlag: item.addFlagShow ? 1 : 0,
        })
    });

    const { code } = index == 1 ? await addGildingInfoApi(data) : await editGildingInfoApi(data);

    if (code == 200) {
        proxy?.$modal.msgSuccess('操作成功');
        emits('submit', false);
    }
};

const handleClose = () => {
    emits('close');
};

</script>

<style lang="scss" scoped>
.import_right {
    width: 100%;
    display: flex;
    justify-content: flex-end;
}


::v-deep .el-upload-dragger {
    padding: 0px 4px !important;
    height: 70px !important;
    width: 160px;
}

.upload_img {
    height: 70px !important;
    width: 160px;
    border: 1px solid #FFFFFF;
    position: relative;
    cursor: pointer;
}

.upload_img_bdr {
    width: 160px;
    height: 70px !important;
    border: 1px solid #3291F8;
    object-fit: contain;
}

.upload_img_del {
    position: absolute;
    right: -10px;
    top: -10px;
    ;
}

.groupFlex {
    height: 70px;
    display: flex;
    align-items: center;
}

.lint {
    width: 90%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>